#pragma once
#include <string>
#include <mysql/mysql.h>
#include "log.h"

class mysql_util
{
public:
    static MYSQL *mysql_create(
        const std::string &host,
        const std::string &user,
        const std::string &pass,
        const std::string &db,
        int port)
    {
        MYSQL *mysql = mysql_init(NULL);
        if(mysql == NULL)
        {
            ERR_LOG("mysql init failed!");
            return NULL;
        }
        if(mysql_real_connect(mysql,host.c_str(),user.c_str(),
            pass.c_str(),db.c_str(),port,NULL,0) == NULL)
        {
            ERR_LOG("mysql connect server failed! %s", mysql_error(mysql));
            mysql_close(mysql);
            return NULL;
        }
        if(mysql_set_character_set(mysql,"utf8mb4")!=0)
        {
            ERR_LOG("mysql set character failed!");
            mysql_close(mysql);
            return NULL;
        }
        bool reconnect = 1;
        mysql_options(mysql, MYSQL_OPT_RECONNECT, &reconnect);
        return mysql;
    }
    static void mysql_destory(MYSQL *mysql)
    {
        if(mysql == NULL)
        {
            return;
        }
        mysql_close(mysql);
        return;
    }
    static bool mysql_exec(MYSQL *mysql,const std::string &sql)
    {
        if(mysql_query(mysql,sql.c_str()) != 0)
        {
            ERR_LOG("SQL: %s", sql.c_str());
            ERR_LOG("ERR: %s", mysql_error(mysql));
            return false;
        }
        return true;
    }
    
};